package com.zxkj.commonpatrol.repoisity;

import android.util.Log;

import androidx.lifecycle.Observer;

import com.allen.library.base.BaseHttpUtil;
import com.allen.library.download.DownloadInterceptor;
import com.allen.library.download.DownloadObserver;
import com.allen.library.factory.ApiFactory;
import com.allen.library.interceptor.Transformer;
import com.allen.library.observer.CommonObserver;
import com.allen.library.utils.HttpConnectionUtil;
import com.czy.basecommon.utils.base.BaseRepository;
import com.czy.basecommon.utils.constant.ItrackConstant;
import com.czy.basecommon.utils.network.AppUrlConfig;
import com.czy.basecommon.utils.tools.SPUtils;
import com.czy.basecommon.utils.tools.TimeTool;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.zxkj.commonpatrol.model.entity.itemPicEntity;
import com.zxkj.commonpatrol.model.entity.itemVioceEntity;
import com.zxkj.commonpatrol.model.post.PostAlarmLogMedioInfo;
import com.zxkj.commonpatrol.model.post.PostAlarmPhotoInfo;
import com.zxkj.commonpatrol.model.post.PostAlarmVedioInfo;
import com.zxkj.commonpatrol.model.post.PostAlarmVoiceInfo;
import com.zxkj.commonpatrol.model.response.MediaInfoResponse;
import com.zxkj.commonpatrol.net.ETFAPi;
import com.zxkj.commonpatrol.net.ETFApiHelper;

import org.json.JSONObject;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

import static com.zxkj.commonpatrol.net.ETFApiHelper.BASE_URL;

public class ShowMediaDetailRepoisity extends BaseRepository {
    private int j = 1;//图片index

    private int k = 1;//语音index

    public ShowMediaDetailRepoisity() {

    }

    public void getAlarmLogMedioInfo(String AlarmId, MyBaseDataCallBack myBaseDataCallBack) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("LoginId", SPUtils.get(ItrackConstant.LOGINID, ""));
        map.put("Token", SPUtils.get(ItrackConstant.TOKEN, ""));
        map.put("Lang", 1);

        PostAlarmLogMedioInfo postAlarmLogMedioInfo = new PostAlarmLogMedioInfo();
        postAlarmLogMedioInfo.setAlarmId(AlarmId);
        ETFApiHelper.geRadomApi().getAlarmLogMedioInfo(map, new BaseHttpUtil<PostAlarmLogMedioInfo>().convertVo2Json(postAlarmLogMedioInfo))
                .compose(Transformer.switchSchedulers())
                .subscribe(new CommonObserver<List<MediaInfoResponse>>() {
                    @Override
                    protected String setTag() {
                        return "down";
                    }

                    @Override
                    protected void onError(String errorMsg) {
                        myBaseDataCallBack.onDataFailCallBack(404, errorMsg);
                    }

                    @Override
                    protected void onSuccess(List<MediaInfoResponse> mediaInfoResponse) {
                        myBaseDataCallBack.onDataSuccessCallBack(mediaInfoResponse);
                    }
                });
    }

    //下载语音数据
    public void DownLoadVoice(String fileName, String path, String VoiceId, int GroupId, int index, List<MediaInfoResponse.MediaVoice> mediaVoiceList,
                              MyBaseDataCallBack myBaseDataCallBack) {


        HashMap<Integer, List<itemVioceEntity>> listHashMap = new HashMap<>();
        HashMap<String, Object> map = new HashMap<String, Object>();
        List<itemVioceEntity> itemVioceEntities = new ArrayList<>();
        map.put("LoginId", SPUtils.get(ItrackConstant.LOGINID, ""));
        map.put("Token", SPUtils.get(ItrackConstant.TOKEN, ""));
        map.put("Lang", 1);


        for (int i = 0; i < mediaVoiceList.size(); i++) {
            String fileNames = null;
            try {
                fileNames = TimeTool.format(System.currentTimeMillis(), TimeTool.format3) + i + ".amr";
            } catch (ParseException e) {
                e.printStackTrace();
            }
            PostAlarmVoiceInfo postAlarmVoiceInfo = new PostAlarmVoiceInfo();
            postAlarmVoiceInfo.setVoiceId(mediaVoiceList.get(i).VoiceId);
            int groupId = mediaVoiceList.get(i).getGroupId();
            postAlarmVoiceInfo.setGroupId(groupId);
            postAlarmVoiceInfo.setIndex(mediaVoiceList.get(i).Index);
            ApiFactory.getInstance()
                    .setOkClient(new OkHttpClient.Builder().addInterceptor(new DownloadInterceptor()).build())
                    .createApi(AppUrlConfig.BASE_KEY, BASE_URL, ETFAPi.class)
                    .downloadAlarmLogVoice(map, new BaseHttpUtil<PostAlarmVoiceInfo>().convertVo2Json(postAlarmVoiceInfo))
                    .compose(Transformer.<ResponseBody>switchSchedulers())
                    .subscribe(new DownloadObserver(fileNames, path) {
                        @Override
                        protected String setTag() {
                            return "down";
                        }
                        @Override
                        protected void onError(String errorMsg) {
                            if (k == mediaVoiceList.size()) {
                                //最后一张
                                if (itemVioceEntities.size() > 0) {
                                    myBaseDataCallBack.onDataSuccessCallBack(itemVioceEntities);
                                } else {
                                    myBaseDataCallBack.onDataFailCallBack(404, errorMsg);
                                }
                                k = 1;
                            } else {
                                k++;
                            }
                        }

                        @Override
                        protected void onSuccess(long bytesRead, long contentLength, float progress, boolean done, String filePath) {
                            if (done) {
                                itemVioceEntities.add(new itemVioceEntity(0, filePath));
//                                if (groupId==1){
//                                    List<itemVioceEntity>  entities1=new ArrayList<>();
//                                    entities1.add(new itemVioceEntity(0, filePath));
//                                    listHashMap.put(1,entities1);
//                                }else if (groupId==2){
//                                    List<itemVioceEntity>  entities2=new ArrayList<>();
//                                    entities2.add(new itemVioceEntity(0, filePath));
//                                    listHashMap.put(2,entities2);
//                                }else{
//                                    List<itemVioceEntity>  entities3=new ArrayList<>();
//                                    entities3.add(new itemVioceEntity(0, filePath));
//                                    listHashMap.put(3,entities3);
//                                }
                                if (k == mediaVoiceList.size()) {
                                    //下载完最后一张了
                                    myBaseDataCallBack.onDataSuccessCallBack(itemVioceEntities);
                                    k = 1;
                                } else {
                                    k++;
                                }
//                                myBaseDataCallBack.onDataSuccessCallBack(filePath);
                            }
                        }
                    });
        }


    }

    //下载图片数据(抛弃)
    public void DownLoadPhoto(String fileName, String path, String PhotoId, int GroupId, int index, List<MediaInfoResponse.MediaPhoto> mediaVoiceList, MyBaseDataCallBack myBaseDataCallBack) {
        HashMap<Integer, List<itemPicEntity>> listHashMap = new HashMap<>();
        HashMap<String, Object> map = new HashMap<String, Object>();
        List<itemPicEntity> itemPicEntityList = new ArrayList<>();
        map.put("LoginId", SPUtils.get(ItrackConstant.LOGINID, ""));
        map.put("Token", SPUtils.get(ItrackConstant.TOKEN, ""));
        map.put("Lang", 1);
        for (int i = 0; i < mediaVoiceList.size(); i++) {
            String fileNames = null;
            try {
                fileNames = TimeTool.format(System.currentTimeMillis(), TimeTool.format3) + i+10 + ".jpeg";
            } catch (ParseException e) {
                e.printStackTrace();
            }


            PostAlarmPhotoInfo postAlarmPhotoInfo = new PostAlarmPhotoInfo();
            postAlarmPhotoInfo.setPhotoId(mediaVoiceList.get(i).PhotoId);
            int groupId = mediaVoiceList.get(i).getGroupId();
            postAlarmPhotoInfo.setGroupId(groupId);
            postAlarmPhotoInfo.setIndex(mediaVoiceList.get(i).Index);

            ApiFactory.getInstance()
                    .setOkClient(new OkHttpClient.Builder().addInterceptor(new DownloadInterceptor()).build())
                    .createApi(AppUrlConfig.BASE_KEY, BASE_URL, ETFAPi.class)
                    .downloadAlarmLogPhoto(map, new BaseHttpUtil<PostAlarmPhotoInfo>().convertVo2Json(postAlarmPhotoInfo))
                    .compose(Transformer.<ResponseBody>switchSchedulers())
                    .subscribe(new DownloadObserver(fileNames, path) {
                        @Override
                        protected String setTag() {
                            return "down";
                        }
                        @Override
                        protected void onError(String errorMsg) {
                            if (j == mediaVoiceList.size()) {
                                if (itemPicEntityList != null && itemPicEntityList.size() > 0) {
                                    myBaseDataCallBack.onDataSuccessCallBack(itemPicEntityList);
                                } else {
                                    myBaseDataCallBack.onDataFailCallBack(404, errorMsg);
                                }
                            } else {
                                j++;
                            }


                        }

                        @Override
                        protected void onSuccess(long bytesRead, long contentLength, float progress, boolean done, String filePath) {
                            if (done) {
//

//                                if (groupId==1){
//                                    List<itemPicEntity>  entities1=new ArrayList<>();
//                                    entities1.add(new itemPicEntity( filePath));
//                                    listHashMap.put(1,entities1);
//                                }else if (groupId==2){
//                                    List<itemPicEntity>  entities2=new ArrayList<>();
//                                    entities2.add(new itemPicEntity( filePath));
//                                    listHashMap.put(2,entities2);
//                                }else{
//                                    List<itemPicEntity>  entities3=new ArrayList<>();
//                                    entities3.add(new itemPicEntity( filePath));
//                                    listHashMap.put(3,entities3);
//                                }
                                itemPicEntityList.add(new itemPicEntity(filePath));
                                if (j == mediaVoiceList.size()) {
                                    //下载完最后一张了
                                    myBaseDataCallBack.onDataSuccessCallBack(itemPicEntityList);
                                    j = 1;
                                } else {
                                    j++;
                                }
//                                myBaseDataCallBack.onDataSuccessCallBack(filePath);
                            }
                        }
                    });
        }

    }


    //下载视频数据
    public void DownLoadVedio(String fileName, String path, String VedioId, int GroupId, int index, MyBaseDataCallBack myBaseDataCallBack) {

        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("LoginId", SPUtils.get(ItrackConstant.LOGINID, ""));
        map.put("Token", SPUtils.get(ItrackConstant.TOKEN, ""));
        map.put("Lang", 1);

        for (int i = 1; i < index + 1; i++) {

            PostAlarmVedioInfo postAlarmVedioInfo = new PostAlarmVedioInfo();
            postAlarmVedioInfo.setVedioId(VedioId);
            postAlarmVedioInfo.setGroupId(GroupId);
            postAlarmVedioInfo.setIndex(index);
            ApiFactory.getInstance()
                    .setOkClient(new OkHttpClient.Builder().addInterceptor(new DownloadInterceptor()).build())
                    .createApi(AppUrlConfig.BASE_KEY, BASE_URL, ETFAPi.class)
                    .downloadAlarmLogVedio(map, new BaseHttpUtil<PostAlarmVedioInfo>().convertVo2Json(postAlarmVedioInfo))
                    .compose(Transformer.<ResponseBody>switchSchedulers())
                    .subscribe(new DownloadObserver(fileName, path) {
                        @Override
                        protected void onError(String errorMsg) {
                            myBaseDataCallBack.onDataFailCallBack(404, errorMsg);
                        }

                        @Override
                        protected void onSuccess(long bytesRead, long contentLength, float progress, boolean done, String filePath) {
                            if (done) {
                                myBaseDataCallBack.onDataSuccessCallBack(filePath);
                            }
                        }
                    });
        }
    }


    //下载首长图片(指定方法,不可复用)

    public  void   DownPo(Map<Integer, MediaInfoResponse.MediaPhoto> maps,MyBaseDataCallBack<Map<Integer, String>> myBaseDataCallBack){

        new Thread(new Runnable() {
            @Override
            public void run() {
                Map<Integer, String> downLoads=new HashMap<>();
                Iterator<Map.Entry<Integer, MediaInfoResponse.MediaPhoto>> entries = maps.entrySet().iterator();


                 next(entries,downLoads);


                myBaseDataCallBack.onDataSuccessCallBack(downLoads);

            }
        }).start();

    }

    public  void  next(Iterator<Map.Entry<Integer, MediaInfoResponse.MediaPhoto>> entries, Map<Integer, String> downLoads){
        if (entries.hasNext()){
            Map.Entry<Integer, MediaInfoResponse.MediaPhoto> entry = entries.next();
            MediaInfoResponse.MediaPhoto value = entry.getValue();

            PostAlarmPhotoInfo postAlarmPhotoInfo = new PostAlarmPhotoInfo();
            postAlarmPhotoInfo.setPhotoId(value.PhotoId);
            int groupId = value.getGroupId();
            postAlarmPhotoInfo.setGroupId(groupId);
            postAlarmPhotoInfo.setIndex(value.Index);
            Map<Object, Object> objectObjectMap = new BaseHttpUtil<PostAlarmPhotoInfo>().MyconvertVo2Params(postAlarmPhotoInfo);
            JSONObject object = new JSONObject(objectObjectMap);
            // 文件名
            String fileNames = null;
            try {
                fileNames = com.allen.library.utils.TimeTool.format(System.currentTimeMillis(), com.allen.library.utils.TimeTool.format3)  + value.GroupId+value.Index+value.getPhotoId()+".jpeg";
            } catch (ParseException e) {
                e.printStackTrace();
            }

            HttpConnectionUtil.downloadFile(ItrackConstant.BASE_URL + "/api/Logs/DownloadAlarmLogPhoto", ItrackConstant.DownPicture, SPUtils.get(ItrackConstant.TOKEN, ""), SPUtils.get(ItrackConstant.LOGINID, ""), object.toString(),fileNames, new HttpConnectionUtil.MyBaseDataCallBack<String>() {
                @Override
                public void onDataSuccessCallBack(String s) {
                    downLoads.put(entry.getKey(),s);



                        next(entries,downLoads);


                }

                @Override
                public void onDataFailCallBack(String s, String t1) {


                        next(entries,downLoads);

                }
            });

        }
        }
















    }




